package com.yanfan.web.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 天气
 *
 * @author ruoyi
 */
@Api(tags = "天气")
@RestController
public class WeatherController {

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("weatherInfo")
    public AjaxResult getRouters() throws IOException {

        Object weatherInfo = redisCache.getCacheObject("weatherInfo");
        String result;
        if(ObjectUtil.isEmpty(weatherInfo)){
            String apiKey = "902603d2ff775d0223385c1ed347f9cd";
            String apiUrl = "http://apis.juhe.cn/simpleWeather/query";

            HashMap<String, String> map = new HashMap<>();
            map.put("key", apiKey);
            map.put("city", "上海");

            URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
            BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response);
            result = response.toString();
            redisCache.setCacheObject("weatherInfo", result, 3, TimeUnit.HOURS);
        }else{
            result = weatherInfo.toString();
        }
        return AjaxResult.success("成功",result);
    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
}
